import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getAuthButtonListApi, getAuthMenuListApi } from "@/api/modules/login";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
//引入 views路由文件
const viewsModules = import.meta.glob<{ routes: Menu.MenuOptions }>("@/routers/viewsModules/*.ts", { eager: true });
const localRoutesConfig = Object.values(viewsModules).map(item => item.routes);
export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: {},
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: ""
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      const { data } = await getAuthButtonListApi();
      this.authButtonList = data;
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = await getAuthMenuListApi();
      this.authMenuList = generateRoutes(data as DataRoute.Route[], localRoutesConfig);
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});

/**
 * 动态生成路由
 * @param dynamicRoutes 接口获取的路由
 * @param localRoutes 本地路由配置
 * @returns
 */
const generateRoutes = (dynamicRoutes: DataRoute.Route[], localRoutes: Menu.MenuOptions[]): Menu.MenuOptions[] => {
  const result = dynamicRoutes.map(dynamicItem => {
    let findResult = localRoutes.find(localItem => localItem.matcher === dynamicItem.routePath);
    if (!findResult) return;
    if (findResult?.children && dynamicItem?.children) {
      findResult = setTitleAndIcon(dynamicItem, findResult);
      findResult.children! = [...(generateRoutes(dynamicItem.children, findResult.children!) as Menu.MenuOptions[])];
      findResult.children.filter(item => item);
      return findResult;
    } else if ((!dynamicItem?.children && findResult.children) || !dynamicItem.children) {
      delete dynamicItem.children;
      findResult = setTitleAndIcon(dynamicItem as DataRoute.Route, findResult);
      return findResult;
    }
  });
  return result.filter(item => item) as Menu.MenuOptions[];
};

const setTitleAndIcon = (dynamicItem: DataRoute.Route, localItem: Menu.MenuOptions) => {
  localItem.meta.title = dynamicItem.title;
  localItem.meta.icon = dynamicItem.icon;
  return localItem;
};
